package co.yixiang.modules.shop.service.impl;

import co.yixiang.modules.shop.domain.YxInfo;
import co.yixiang.modules.shop.repository.YxInfoRepository;
import co.yixiang.modules.shop.service.YxInfoService;
import co.yixiang.modules.shop.service.dto.YxInfoDTO;
import co.yixiang.modules.shop.service.dto.YxInfoQueryCriteria;
import co.yixiang.modules.shop.service.mapper.YxInfoMapper;
import co.yixiang.mp.domain.YxArticle;
import co.yixiang.utils.PageUtil;
import co.yixiang.utils.QueryHelp;
import co.yixiang.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Optional;


@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxInfoServiceImpl implements YxInfoService {

    @Autowired
    private YxInfoRepository yxInfoRepository;

    @Autowired
    private YxInfoMapper yxInfoMapper;

    /**
     * 查询数据分页
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> queryAll(YxInfoQueryCriteria criteria, Pageable pageable) {
        Page<YxInfo> page = yxInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteriaQuery, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(yxInfoMapper::toDto));
    }

    /**
     * 创建
     *
     * @param resources
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public YxInfoDTO create(YxInfo resources) {
        return yxInfoMapper.toDto(yxInfoRepository.save(resources));
    }

    /**
     * 修改
     *
     * @param resources
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(YxInfo resources) {
        Optional<YxInfo> optionalYxArticle = yxInfoRepository.findById(resources.getId());
        ValidationUtil.isNull(optionalYxArticle, "YxInfo", "id", resources.getId());
        YxInfo yxInfo = optionalYxArticle.get();
        yxInfo.copy(resources);
        yxInfoRepository.save(yxInfo);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        yxInfoRepository.deleteById(id);
    }
}
